/**
 * Created by ${PRODUCT_NAME}.
 * User: skylerparr
 * Date: 12/12/10
 * Time: 8:37 AM
 * To change this template use File | Settings | File Templates.
 */
package com.thoughtorigin.util {
import com.thoughtorigin.module.ModuleLoader;

import com.thoughtorigin.reflect.Describe;

import flash.system.ApplicationDomain;
import flash.utils.Dictionary;

public class ClassCreator implements Instantiator {

    private var _moduleLoader: ModuleLoader;

    public function ClassCreator() {
    }

    public static function create(clazz: Class, args: Array): Object {
        if(!args) {
            return new clazz();
        }

        var i: uint = 0;
        switch(args.length) {
            case 0:
                return new clazz();
            case 1:
                return new clazz(args[i]);
            case 2:
                return new clazz(args[i++], args[i++]);
            case 3:
                return new clazz(args[i++], args[i++], args[i++]);
            case 4:
                return new clazz(args[i++], args[i++], args[i++], args[i++]);
            case 5:
                return new clazz(args[i++], args[i++], args[i++], args[i++], args[i++]);
            case 6:
                return new clazz(args[i++], args[i++], args[i++], args[i++], args[i++], args[i++]);
            case 7:
                return new clazz(args[i++], args[i++], args[i++], args[i++], args[i++], args[i++], args[i++]);
            case 8:
                return new clazz(args[i++], args[i++], args[i++], args[i++], args[i++], args[i++], args[i++], args[i++]);
            case 9:
                return new clazz(args[i++], args[i++], args[i++], args[i++], args[i++], args[i++], args[i++], args[i++], args[i++]);
        }

        throw new ReferenceError("Only allowed to create instances with less than 9 arguments");
    }

    public function create(clazz:Class, args:Array):Object {
        var describedXML: XML = Describe.type(clazz);
        var className: String = describedXML.@name;
        return createByClassName(className, args);
    }

    [Inject]
    public function set moduleLoader(value: ModuleLoader): void {
        _moduleLoader = value;
    }

    public function createByClassName(className:String, args:Array):Object {
        return ClassCreator.create(getClassByName(className), args);
    }

    public function getClassByName(className:String):Class {
        var retVal: Class = _moduleLoader.getClassByName(className);
        if(!retVal) {
            throw new ObjectCreationError("unable to create object, " + className + " was not found.");
        }
        return retVal;
    }
}
}
